package com.lrj.api.handler;

import com.alibaba.fastjson.JSON;
import com.lrj.api.annotation.ApiResponse;
import com.lrj.common.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class GlobalHandler implements ResponseBodyAdvice {

  @ExceptionHandler({Exception.class, ArithmeticException.class})
  public Result exceptionHandler(Exception e) {
    e.printStackTrace();
    return Result.fail("系统异常，请联系管理员");
  }

  @ExceptionHandler(RuntimeException.class)
  public Result runtimeExceptionHandler(RuntimeException e) {
    e.printStackTrace();
    return Result.fail(e.getMessage());
  }

  public boolean supports(MethodParameter methodParameter, Class aClass) {
    if (methodParameter.getMethodAnnotation(ApiResponse.class) != null
            || methodParameter.getDeclaringClass().getAnnotation(ApiResponse.class) != null)
    {
      return true;
    }
    return false;
  }

  public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
    Result result = Result.ok(o);
    if (o instanceof String) {
      serverHttpResponse.getHeaders().set("content-type", "application/json;charset=utf-8");
      return JSON.toJSONString(result);
    } else {
      return result;
    }
  }
}
